package com.soc.auth.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.soc.auth.propertires.AliyunSmsProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 阿里云短信业务类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AliyunSmsService {

    private final AliyunSmsProperties aliyunSmsProperties;

    /**
     * 发送短信验证码
     *
     * @param phoneNumber 手机号
     * @param code 验证码
     */
    public boolean sendSmsCode(String phoneNumber, String code) {

        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile(
                aliyunSmsProperties.getRegionId(),
                aliyunSmsProperties.getAccessKeyId(),
                aliyunSmsProperties.getAccessKeySecret());
        try {
            DefaultProfile.addEndpoint(
                    "cn-hangzhou",
                    aliyunSmsProperties.getRegionId(),
                    aliyunSmsProperties.getProduct(), aliyunSmsProperties.getDomain());
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);

        // 组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        // 必填:待发送手机号
        request.setPhoneNumbers(phoneNumber);
        // 必填:短信签名-可在短信控制台中找到
        request.setSignName(aliyunSmsProperties.getSignName());
        // 必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(aliyunSmsProperties.getTemplateCode());
        // 必填:在设置短信模板的时候有一个占位符
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        try {
            SendSmsResponse response = acsClient.getAcsResponse(request);
            if(response.getCode()!= null && "OK".equals(response.getCode())){
                log.info("手机号：{} 短信发送成功！", phoneNumber);
                return true;
            }else {
                log.error("手机号：{} 短信发送失败！", phoneNumber);
                throw new RuntimeException("手机号：" + phoneNumber + "短信发送失败：" + response.getMessage());
            }
        }catch (Exception e) {
            log.error("手机号：{} 短信发送失败！", phoneNumber);
            e.printStackTrace();
        }

        return false;
    }
}
